import java.io.StringReader;
import java.util.List;

import javax.xml.xpath.*;



import org.w3c.dom.*;

import org.w3c.tidy.Tidy;
import org.xml.sax.InputSource;




public class XpathShoter {
	public static String shorter(String strXpath,String html) throws XPathExpressionException
	{
		String spath="";
		XPathFactory factory=XPathFactory.newInstance();  
		XPath xPath=factory.newXPath();  
		Tidy tidy = new Tidy();
		tidy.setQuiet(true);
		tidy.setShowWarnings(false);
		tidy.setXmlTags(true);
		Document doc = tidy.parseDOM(new StringReader(html), null);
		if(strXpath=="")
		assert strXpath!="";
		assert doc!=null;
		
		strXpath = strXpath.replaceAll("\\s", "");
		System.err.println(strXpath);
		xPath.compile("//b");
		Object oresult = xPath.evaluate(strXpath,doc,XPathConstants.NODESET);
		assert oresult!=null;
		NodeList result = (NodeList)oresult;
		
		if(result.getLength()!=1){System.out.println("strXpath Wrong!!"); return null;}
		while(true)
		{
			
			
			int index=strXpath.lastIndexOf("/");
			if(index==0)break;
			//System.out.println(index);
			spath = "/"+strXpath.substring(index)+spath;
			strXpath = strXpath.substring(0, index);
			//System.out.println(strXpath);
			
			NodeList  sresult = (NodeList )xPath.evaluate(spath,doc, XPathConstants.NODESET);
			//System.out.println(spath+"\n"+sresult.getLength());
			if(sresult.getLength()!=1);//{System.out.println("SResult not a unique !");}
			else if(sresult.item(0).equals(result.item(0)))break;
			if(strXpath=="")break;
			//System.out.println(spath);
		}
		//System.out.println("out simplifyXpath");
		return spath;
	}

}
